package com.blkj.iam.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.config.SaSignConfig;
import cn.dev33.satoken.sign.SaSignTemplate;
import cn.dev33.satoken.sso.template.SaSsoServerTemplate;
import com.blkj.iam.system.model.entity.Client;
import com.blkj.iam.system.service.ClientService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hujingbo
 */
@Component
@RequiredArgsConstructor
public class CustomSaSsoServerTemplate extends SaSsoServerTemplate {

    private final ClientService clientService;

    // 存储所有 client 的秘钥
    private static Map<String, SaSignTemplate> signMap = new HashMap<>();

    @PostConstruct
    public void initSignMap() {
        // 从数据库中查询所有客户端信息
        List<Client> clients = clientService.list();
        for (Client client : clients) {
            // 创建 SaSignTemplate 并添加到 signMap
            SaSignTemplate saSignTemplate = new SaSignTemplate(new SaSignConfig(client.getAppKey()));
            signMap.put(client.getAppId(), saSignTemplate);
        }
    }

    @Override
    public SaSignTemplate getSignTemplate(String client) {
        // 先从自定义的 signMap 中获取
        SaSignTemplate saSignTemplate = signMap.get(client);
        if (saSignTemplate != null) {
            return saSignTemplate;
        }
        // 找不到就返回全局默认的 SaSignTemplate
        return SaManager.getSaSignTemplate();
    }
}
